import React from 'react';
import {inject, observer} from 'mobx-react';
import { Route, withRouter, Switch } from 'react-router-dom';
import { ListPage , Comment, Reply, CKRichText, AtSomeone } from 'weaver-mobile-page';
import { Avatar, Tools, Modal } from 'weaver-mobile';
import { toJS} from 'mobx';
import EditDiscussData from './editDiscussData';
let getLabel = Tools.getLabel

@inject('viewWorkplanStore')
@withRouter
@observer
class DiscussView extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
        //打开附件
        window.openWorkplanDiscussDoc = (t, showid, workplanid) => {
          if (window.openLink){
            window.openLink(`/spa/document/static4mobile/index.html#/attach/${showid}?workplanid=${workplanid}&fromModule=workplan`)
          }
        }
        window.openWorkplanAppLink = (linkType, linkid, workplanid, isPro=false) => {
          if (linkType == 'doc')
            window.openLink(`/spa/document/static4mobile/index.html#/doc/${linkid}?workplanid=${workplanid}`)
          else if (linkType == 'task')
            return;//手机端暂不支持
          else if (linkType == 'crm')
            window.openLink(`/spa/crm/static4mobile/index.html/#/customerCard/${linkid}`)
          else if (linkType == 'workflow')
            window.openLink(`/spa/workflow/static4mobileform/index.html#/req?fromModul=workplan&modulResourceId=${workplanid}&requestid=${linkid}`)
          else if (linkType == 'project')
            return;//手机端暂不支持
          else
            return false
        }
    }

    componentDidMount() {
      const pathName = this.props.location.pathname      
      const { getExchangeHrmList,workplanid } = this.props.viewWorkplanStore;
      getExchangeHrmList({workplanid:workplanid?workplanid:localStorage.getItem('workid')},pathName)
    }
    componentWillMount() {
 
    }

    getQuery = (search)=>{
      let params ={}
      search.map((v,index)=>{
        const tempV = v.split('=');
        params[tempV[0]] = tempV[1];
        return '';
      });
      return params
    }
    render() {
        const { comment, reply, submitReply, setPageNum, writeReply, setExchangeText, replySubmitLoading } = this.props.viewWorkplanStore;
        const discussHeight = this.getHeight();
        const leftConfig = [
          { type: 'voice' },
          { type: 'blog-biaoqing' },
          // { type: '@' },
          { type: 'tianjia' },
        ];
        setPageNum(0)
        const config = {
          browserContextMenuOnCtrl: false,
          enableContextMenu: false,
        }
        return (
        <div style={{height:discussHeight,WebkitOverflowScrolling: 'touch'}}>
            <Comment
              style={{borderBottom:'1px solid #ddd',height:'100%'}}
              store={comment}
            />
            <Reply
              wrappedComponentRef={ref =>this.replyRef = ref}
              store={reply}
              showOutInput={!replySubmitLoading}
              defaultShow={true}
              showOutTabBar={false}
              visible={false}
              leftConfig={leftConfig}
              onSubmit={datas => {this.onSubmit(datas)}}
              renderAt={item => this.renderAt(item)}
            />
            <Route
              key="editDiscuss"
              path={`**/detail/discussData/editDiscuss`}
              render={()=>(
                <div id="edit">
                  <EditDiscussData />
                </div>
              )}
            />
        </div>
        )
    }

    onBrowserChange = (key, datas) => {
      const { viewWorkplanStore: { writeReply } } = this.props;
      datas.map(v => {
        if(key === 'template'){
          const store = this.getStore();
          const { blogText} = store;
          if(blogText){
            Modal.alert(getLabel(505615,'替换当前内容？'),'', [
              { text: getLabel(31129, '取消') },
              {
                text: getLabel(33703, '确认'),
                onPress: () => {
                  writeReply.setData({richText: `${v.name}`});
                }
              },
            ])
          }else{
            writeReply.setData({richText: `${v.name}`});
          }
          
        }else{
          writeReply.insertHtml(`<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" linktype="${key}" onclick="try{return openAppLink(this,${v.id});}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;`);
        }
      });
    }
  
    //附件上传后事件
    onUploadChange = (key, datas) => {
      const { viewWorkplanStore: { writeReply } } = this.props;
      let str="";
      datas.map(item => {
              str = `<a href='javascript:void(0)' onclick='try{opendoc1(${item.fileid},this);return false;}catch(e){}' ondblclick='return false;' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>
              &nbsp;<a href='javascript:void(0)'  onclick='try{downloads(${item.imagefileid},this,"${item.filename}");return false;}catch(e){}' unselectable='off' target='_blank' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>下载(${item.filesize})</a></br>`;
              writeReply.insertHtml(str);
      });
    }

    onSubmit = (data) => {
      const { submitReply } = this.props.viewWorkplanStore;
      submitReply(data);
      this.replyRef.setVisible(false,()=>{})
    }

    renderAt = (item) =>{
      const { exchangeListStore, atList, atUserStore } = this.props.viewWorkplanStore;
      const template2 = {
        default: {
            theme: 'col2_row2',
            dataKeys: ['data', 'jobtitlename', 'subcompanyname', 'departmentname'],
        },
      };
      return( <div>
        <div onClick={this.goHrmList}>
        {item}
        </div>
        <AtSomeone
          datas={toJS(atList)}
          template={template2}
          store={atUserStore}
          onOk={(datas = []) => {
            this.atChange2(datas);
          }}
          imgSrcDataKey={'icon'}
          nameDataKey={'data'}
        />
      </div>
      )
      // let mobileshowtemplate = {};
      // mobileshowtemplate = {
      //   default: [
      //     {
      //       key: 'col1',
      //       style: { flex: 'none' },
      //       render(a) {
      //         return <Avatar name={toJS(a).name} url={toJS(a).url} />;
      //       },
      //     },
      //     {
      //       key: 'col2',
      //       configs: [
      //         { key: 'col2-row1', configs: [{ key: 'name' }],style:{color:'#333'} },
      //         { key: 'col2-row2', configs: [{ key: 'desc' }] },
      //       ],
      //     },
      //   ],
      // };
      // return(
      //   <div>
      //     <div onClick={this.goHrmList}>
      //     {item}
      //     </div>
      //     <ListPage
      //       showCheck
      //       multipleCheck={true}
      //       isRowClickCheck
      //       onRowClick={(newKeys,data)=>{
      //         // console.log(newKeys,data)
      //       }}
      //       template={mobileshowtemplate}
      //       store={exchangeListStore}
      //       buttonGroupData={[{
      //           key: 'clear',
      //           text: '取消',
      //           onClick: () => {this.props.history.go(-1)},
      //         },
      //         {
      //           key: 'submit',
      //           text: '确定',
      //           onClick: () => {this.atChange();this.props.history.go(-1)},
      //           type: 'primary',
      //         },]}
      //     >
      //     </ListPage>
      //     </div>
      // )
    }

    // @ 事件
  atChange = () => {
    const { reply: { setState,atLists } ,exchangeListStore,atUserStore} = this.props.viewWorkplanStore;
    const data = exchangeListStore.datas;
    const selectedRowKeys = exchangeListStore.selectedRowKeys;
    let datas=[];
    selectedRowKeys&&selectedRowKeys.forEach((id,index)=>{
      data.forEach((element,index)=>{
        if(element.id === id){
          datas.push(element)
        }
      })
    })
    let dataLen = 0;
    setState({ atList: [],
      atLists: [
        ...toJS(atLists),
        ...datas,
      ], });
    if (datas && datas.length > 0) {
      let html = '';
      datas.map((item) => {
        const value = `@${item.name}`;
        html += `<a contenteditable="false" atsome="@${item.id}" atsome-uid="${item.id}" atsome-name="${item.name}" target="_blank" style="cursor:pointer;text-decoration:none !important;color:#2777c1!important;" href="javascript:void(0)">${value}</a>&nbsp;`;
      });
      this.replyRef.replyRef.changeTextValue(html);
    }
  }

  atChange2 = (datas) => {
    const { reply: { setState,atLists } ,atUserStore} = this.props.viewWorkplanStore;
    let dataLen = 0;
    setState({ atList: [],
      atLists: [
        ...toJS(atLists),
        ...datas,
      ], });
    if (datas && datas.length > 0) {
      let html = '';
      datas.map((item) => {
        const value = `@${item.data}`;
        html += `<a contenteditable="false" atsome="@${item.id}" atsome-uid="${item.id}" atsome-name="${item.data}" target="_blank" style="cursor:pointer;text-decoration:none !important;color:#2777c1!important;" href="javascript:void(0)">${value}</a>&nbsp;`;
      });
      this.replyRef.replyRef.changeTextValue(html);
    }
  }

    goHrmList = ()=>{
      const { reply,exchangeListStore, atUserStore } = this.props.viewWorkplanStore;
      this.props.history.push(atUserStore.path)
    }

    getHeight = () => {
      return document.body.clientHeight - (45)*window.getThemeVars()['hd'];
  }
}

export default DiscussView;